package org.praktika.api.service;

import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.praktika.api.dto.OrderCityDto;
import org.praktika.api.entity.OrderCity;
import org.praktika.api.repository.OrderCityRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class OrderCityService {
    private final OrderCityRepository orderCityRepository;
    private final TurOrderService turOrderService;
    private final CityService cityService;
    private final ModelMapper modelMapper = new ModelMapper();

    @Transactional
    public OrderCityDto saveOrderCity(OrderCityDto orderCityDto) {
        OrderCity orderCity = modelMapper.map(orderCityDto, OrderCity.class);
        orderCityRepository.save(orderCity);
        return modelMapper.map(orderCity, OrderCityDto.class);
    }

    public OrderCityDto getOrderCityDtoById(Long id) {
        return modelMapper.map(getOrderCityById(id), OrderCityDto.class);

    }

    public OrderCity getOrderCityById(Long id) {
        Optional<OrderCity> orderCity = orderCityRepository.findById(id);
        return orderCity.orElseThrow(() -> new RuntimeException("No order city found"));
    }

    @Transactional
    public OrderCityDto updateOrderCity(OrderCityDto orderCityDto) {
        OrderCity orderCity = getOrderCityById(orderCityDto.getId());
        orderCity.setCity(cityService.getCityById(orderCityDto.getCity().getId()));
        orderCity.setTurOrder(turOrderService.getTurOrderById(orderCityDto.getTurOrder().getId()));
        orderCity.setDateStart(orderCityDto.getDateStart());
        orderCity.setDateExpiration(orderCityDto.getDateExpiration());
        orderCityRepository.save(orderCity);
        return modelMapper.map(orderCity, OrderCityDto.class);
    }

    @Transactional
    public void deleteOrderCity(Long id) {
        orderCityRepository.deleteById(id);
    }
    public List<OrderCityDto> findAllOrderCity() {
        List<OrderCity> orderCityList = orderCityRepository.findAll();
        List<OrderCityDto> orderCityDtoList = new ArrayList<>();
        orderCityList.forEach(orderCity -> orderCityDtoList.add(modelMapper.map(orderCity, OrderCityDto.class)));
        return orderCityDtoList;
    }
}

